<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/vue/2.6.14/vue.js" type="application/javascript"
  ></script>
</head>
<body>
<div id="app">
  <!--  <img :src="imgPath" v-imgerror alt="">-->
  <img :src="imgPath" v-imgerror="defaultImgPath" alt="">
  <img :src="imgPath" v-imgerror="'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'" alt="">
</div>
</body>
<script>
  // 什么是指令
  // v-xxx开头的自定义属性,例如v-if,v-show..// 什么是自定义指令
  // 自己定义v-xxx开头的自定义属性
  // Vue.directive('imgerror', {
  //   inserted(el) {
  //     el.onerror = function() {
  //       this.src = 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'
  //     }
  //   }
  // })
  Vue.directive('imgerror', {
    inserted(el, binding) {
      // 如果最开始没有值。给默认值
      if (!el.src) {
        el.src = binding.value
      }
      el.onerror = function() {
        this.src = binding.value
      }
    },
    update(el, binding) {
      if (!el.src) {
        el.src = binding.value
      }
    }
  })
  new Vue({
    data() {
      return {
        // imgPath: 'http://localhost:8080/undefined',
        imgPath: undefined,
        defaultImgPath: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'
      }
    },
    mounted() {
      setTimeout(() => {
        this.imgPath = null
      }, 1000)
    },
    methods: {},
    el: '#app'
  })
</script>
</html>
